<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本统计量分析</span>
      </div>
      
      <!-- 搜索和过滤区域 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="设备编号">
          <el-input v-model="queryParams.equipmentNo" placeholder="请输入设备编号"></el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="statisticsData"
        border
        style="width: 100%">
        <el-table-column
          prop="index"
          label="指标"
          width="180">
        </el-table-column>
        <el-table-column
          prop="count"
          label="数量"
          width="120">
        </el-table-column>
        <el-table-column
          prop="mean"
          label="平均值"
          width="120">
        </el-table-column>
        <el-table-column
          prop="std"
          label="标准差"
          width="120">
        </el-table-column>
        <el-table-column
          prop="min"
          label="最小值"
          width="120">
        </el-table-column>
        <el-table-column
          prop="25"
          label="25%分位数"
          width="120">
        </el-table-column>
        <el-table-column
          prop="50"
          label="中位数"
          width="120">
        </el-table-column>
        <el-table-column
          prop="75"
          label="75%分位数"
          width="120">
        </el-table-column>
        <el-table-column
          prop="max"
          label="最大值"
          width="120">
        </el-table-column>
      </el-table>

      <!-- 图表展示 -->
      <div id="statisticsChart" style="width: 100%; height: 400px; margin-top: 20px"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getToken } from '@/utils/auth'
import axios from 'axios'

export default {
  name: 'BasicStatistics',
  data() {
    return {
      // 加载状态
      loading: false,
      // 查询参数
      queryParams: {
        equipmentNo: '',
        dateRange: []
      },
      // 统计数据
      statisticsData: [],
      // 图表实例
      chart: null
    }
  },
  created() {
    this.getStatisticsData()
  },
  mounted() {
    // 初始化图表
    this.initChart()
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.resizeChart)
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    // 获取统计数据
    async getStatisticsData() {
      this.loading = true
      try {
        const response = await axios.get(`${process.env.VUE_APP_BASE_API}/statistics/basic`, {
           params: {
            equipmentNo: this.queryParams.equipmentNo,
            startDate: this.queryParams.dateRange ? this.queryParams.dateRange[0] : '',
            endDate: this.queryParams.dateRange ? this.queryParams.dateRange[1] : ''
          },
          headers: {
            'Authorization': 'Bearer ' + getToken()
          }
        })

        if (response.data && response.data.code === 200) {
          // 转换数据格式
          this.statisticsData = this.transformData(response.data.data)
          // 更新图表
          this.updateChart()
        } else {
          this.$message.error(response.data.msg || '获取统计数据失败')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取统计数据失败')
      } finally {
        this.loading = false
      }
    },

    // 转换数据格式
    transformData(data) {
      const result = []
      for (const [key, value] of Object.entries(data)) {
        result.push({
          index: key,
          count: value.count || 0,
          mean: value.mean ? Number(value.mean).toFixed(2) : 0,
          std: value.std ? Number(value.std).toFixed(2) : 0,
          min: value.min || 0,
          '25': value.percentile25 || 0,
          '50': value.percentile50 || 0,
          '75': value.percentile75 || 0,
          max: value.max || 0
        })
      }
      return result
    },

    // 初始化图表
    initChart() {
      this.chart = echarts.init(document.getElementById('statisticsChart'))
      this.updateChart()
    },

    // 更新图表数据
    updateChart() {
      if (!this.chart || !this.statisticsData.length) return

      const option = {
        title: {
          text: '基本统计量分析图',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['平均值', '标准差', '最大值', '最小值'],
          top: 30
        },
        xAxis: {
          type: 'category',
          data: this.statisticsData.map(item => item.index),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '平均值',
            type: 'bar',
            data: this.statisticsData.map(item => item.mean)
          },
          {
            name: '标准差',
            type: 'bar',
            data: this.statisticsData.map(item => item.std)
          },
          {
            name: '最大值',
            type: 'line',
            data: this.statisticsData.map(item => item.max)
          },
          {
            name: '最小值',
            type: 'line',
            data: this.statisticsData.map(item => item.min)
          }
        ]
      }

      this.chart.setOption(option)
    },

    // 处理查询
    handleQuery() {
      this.getStatisticsData();
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        equipmentNo: '',
        dateRange: []
      }
      this.getStatisticsData()
    },

    // 调整图表大小
    resizeChart() {
      this.chart && this.chart.resize()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.demo-form-inline {
  margin-bottom: 20px;
}
</style> 